/*
 * @Author: your name
 * @Date: 2020-06-08 15:20:53
 * @LastEditTime: 2020-07-06 13:35:10
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \IM_Web\im_web\src\store\actions\initNimSDK.js
 */
import util from '@/utils'
import config from '@/configs'
import SDK from "@/js/js/NIM_Web_NIM_v7.6.0"
import { Message } from 'iview'
import router from '../../router';
import store from '../'

import Tinode from 'tinode-sdk';
import { connect } from './connect'


import { onSessions, onUpdateSession } from './session'
import { onSysMsgs, onSysMsg, onSysMsgUnread, onCustomSysMsgs } from './sysMsgs'
import { onRoamingMsgs, onOfflineMsgs, onMsg } from './msgs'
import { onMyInfo, onUserInfo } from './userInfo'
import { onTeams, onSynCreateTeam, onCreateTeam, onUpdateTeam, onTeamMembers, onUpdateTeamMember, onAddTeamMembers, onRemoveTeamMembers, onUpdateTeamManagers, onDismissTeam, onUpdateTeamMembersMute, onTeamMsgReceipt } from './team'



export function initTinodeNim({ state, commit, dispatch }, loginInfo) {
    console.log(state, commit, dispatch, loginInfo)
    // const APP_NAME = 'TinodeWeb/' + (config.PACKAGE_VERSION || '0.16');
    if (state.nim) {
        state.nim.disconnect()
    }
    window.nim = state.nim = tnSetup()
    // window.nim = state.nim = new Tinode(APP_NAME, config.serverAddress, config.API_KEY, true, false);
    // window.nim = state.nim = new Tinode(APP_NAME, config.serverAddress, config.API_KEY, null, false);
    state.nim.enableLogging(true)
    state.nim.onConnect = connect(loginInfo)
    state.nim.onDisconnect = function (err) {
        console.log('initSDKERR------->', err)
        Message.error(err.message)
    };
    state.nim.onData = function (data) {
        console.log('initSDKData------->', data)
        const topic = state.nim.getTopic(this.state.userUID);
        const newState = { messages: [] };
        topic.messages((m) => {
            console.log(m)
            if (!m.deleted) {
                newState.messages.push(m);
            }
        });
    }
    state.nim.onAutoreconnectIteration = function (data) {
        console.log('onAutoreconnectIteration', data)
    }
    state.nim.onNetworkProbe = function (res) {
        console.log('onNetworkProbe------>',res)
    }
}


function tnSetup() {
    const APP_NAME = 'TinodeWeb/' + (config.PACKAGE_VERSION || '0.16');
    const tinode = new Tinode(APP_NAME, config.serverAddress, config.API_KEY, null, false);
    return tinode;
}

// let loginInfo_1 = { uid: 'yy0giq60102', sdktoken: 'ca9c370f9ed4cf5fa6f146a229fa68da' }
export function initNimSDK({ state, commit, dispatch }, loginInfo) {
    // console.log(commit)
    // console.log(dispatch)
    if (state.nim) {
        state.nim.disconnect()
    }
    // if (!SDK.support.db) {
    //     // this.$message.error(
    //     //     "当前浏览器不支持数indexDB数据库，请更换到主流浏览器，如：Chrome浏览器，火狐浏览器"
    //     // );
    //     Notice.warning({
    //         title: "重要通知",
    //         desc:
    //             "为了保证更好的体验，建议您更新浏览器到最新版或使用Chrome、FireFox、Safari、360等主流浏览器。",
    //         duration: 0
    //     });
    //     // return false;
    // }
    window.nim = state.nim = SDK.getInstance({
        debug: false,
        appKey: "e91925557e9c5fe41901fe93971b42f1",
        account: loginInfo.uid,
        token: loginInfo.sdktoken,
        syncSessionUnread: true,
        syncRobots: true,
        autoMarkRead: true, // 默认为true
        onconnect: function onConnect(event) {
            if (loginInfo) {
                // 连接上以后更新uid
                commit('updateUserUID', loginInfo)
                console.log(event)
                // console.log(loginInfo, "1111", event)
                Message.destroy()
                sessionStorage.setItem('loading', false)
            }
        },
        onerror: function onError(event) {
            // alert(JSON.stringify(event))
            console.log(event)
            // debugger
            Message.error('网络连接状态异常')
            // router.push('/login')
        },
        onwillreconnect: function onWillReconnect(event) {
            console.log(event)
            // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
            console.log('即将重连');
            console.log(event.retryCount);
            console.log(event.duration);
            Message.loading({
                content: '网络异常，正在重新建立连接',
                duration: 0,
                background: true
            });
        },
        ondisconnect: function onDisconnect(error) {
            console.log(error)
            switch (error.code) {
                // 账号或者密码错误, 请跳转到登录页面并提示错误
                case 302:
                    Message.error("帐号或密码错误")
                    router.push('/login')
                    break
                // 被踢, 请提示错误后跳转到登录页面
                case 'kicked':
                    {
                        let map = {
                            PC: '电脑版',
                            Web: '网页版',
                            Android: '手机版',
                            iOS: '手机版',
                            WindowsPhone: '手机版'
                        }
                        let str = error.from
                        let errorMsg = `你的帐号于${util.formatDate(new Date())}被${(map[str] || '其他端')}踢出下线，请确定帐号信息安全!`
                        sessionStorage.clear()
                        Message.error(errorMsg);
                        router.push('/login');
                        break
                    }
                default:
                    break
            }
        },
        // 用户名片 - actions/userInfo
        onmyinfo: onMyInfo,
        onupdatemyinfo: onMyInfo,
        onusers: onUserInfo,
        onupdateuser: onUserInfo,
        // // 群组
        onteams: onTeams,
        onsynccreateteam: onSynCreateTeam,
        syncTeams: true,
        onteammembers: onTeamMembers,
        onCreateTeam: onCreateTeam,
        onDismissTeam: onDismissTeam,
        onUpdateTeam: onUpdateTeam,
        onAddTeamMembers: onAddTeamMembers,
        onRemoveTeamMembers: onRemoveTeamMembers,
        onUpdateTeamManagers: onUpdateTeamManagers,
        onupdateteammember: onUpdateTeamMember,
        onUpdateTeamMembersMute: onUpdateTeamMembersMute,
        onTeamMsgReceipt: onTeamMsgReceipt,
        // // 会话
        onsessions: onSessions,
        onupdatesession: onUpdateSession,
        // // 消息
        onroamingmsgs: onRoamingMsgs,
        onofflinemsgs: onOfflineMsgs,
        onmsg: onMsg,
        // // 系统通知
        onsysmsg: onSysMsg,
        onofflinesysmsgs: onSysMsgs,
        onupdatesysmsg: onSysMsg, // 通过、拒绝好友申请会收到此回调

        onsysmsgunread: onSysMsgUnread,
        onupdatesysmsgunread: onSysMsgUnread,
        onofflinecustomsysmsgs: onCustomSysMsgs,
        oncustomsysmsg: onCustomSysMsgs,
        // // 同步完成
        onsyncdone: function onSyncDone() {
            dispatch('hideLoading')
            // 说明在聊天列表页
            if (store.state.currSessionId) {
                dispatch('setCurrSession', store.state.currSessionId)
            }
        }
    })
    window.nim.useDb = config.useDb
}